package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.helper.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
@Transactional
@Slf4j
@RequiredArgsConstructor
public class TaskServiceImpl implements TaskService {

    //Taskinfo
    private final TaskinfoMapper taskinfoMapper;

    //taskLogInfo
    private final TaskinfoLogsMapper taskinfoLogsMapper;

    //Redis
    private final CacheService cacheService;

    /**
     * 添加延迟任务
     *
     * @param task
     */
    @Override
    public long addTask(Task task) {

        //1.添加任务到数据库中
        boolean success = addTaskToDb(task);

        //2.添加任务到redis中
        if (success) {

            addTaskToCache(task);
        }

        return task.getTaskId();
    }


    /**
     * 取消任务
     *
     * @param taskId
     * @return
     */
    @Override
    public boolean cancelTask(Long taskId) {

        boolean flage = false;

        //1.删除数据库 任务 更新任务日志
        Task task = updateDb(taskId, ScheduleConstants.CANCELLED);

        //2.删除redis中的数据
        if (task != null) {
            removeTaskFromCache(task);
            flage = true;
        }

        return flage;
    }


    /**
     * 按照类型和优先级 拉取任务
     *
     * @param type
     * @param priority
     * @return
     */
    @Override
    public Task poll(int type, int priority) {

        Task task=null;

        try {
            //设置key
            String key=type+"_"+priority;

            //从redis中拉取数据
            String task_json = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
            if (StringUtils.isNotBlank(task_json)) {

                task=JSON.parseObject(task_json,Task.class);

                 //修改数据库信息 为已完成
                updateDb(task.getTaskId(), ScheduleConstants.EXECUTED);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("pool task error", e);
        }

        return task;

    }

    /**
     * 未来数据定时刷新
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh() {

        //加分布式锁 设置时间为30s
        String token = cacheService.tryLock("FUTRUE_TASH_SYNC", 1000 * 30);

        if(StringUtils.isNotBlank(token)) {

            log.info("未来数据定时刷新---定时任务");

            //获取所有未来数据的集合key
            Set<String> FutureKeys = cacheService.scan(ScheduleConstants.FUTURE);

            for (String Futurekey : FutureKeys) {

                //获取当前数据的key topic
                String topicKey = ScheduleConstants.TOPIC + Futurekey.split(ScheduleConstants.FUTURE)[1];

                //按照key和分值查询扶符合条件的数据
                Set<String> tasks = cacheService.zRangeByScore(Futurekey,  0, System.currentTimeMillis());

                //同步数据
                if (!tasks.isEmpty()) {
                    cacheService.refreshWithPipeline(Futurekey,topicKey,tasks);
                    log.info("refresh tasks success");
                }
            }
        }



    }


    /**
     * 数据库任务定时同步到redis   每五分钟执行
     */
    @PostConstruct//指定该方法为初始化方法 服务启动便会执行
    @Scheduled(cron = "0 */5 * * * ?")
    public void reloadData(){

        //1.清理缓存数据
        clearCache();

        //2.查询符合条件的数据 小于未来五分钟的数据
        //获取五分钟后的时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);

        List<Taskinfo> taskinfos = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().lt(Taskinfo::getExecuteTime, calendar.getTime()));

        if(taskinfos.size()>0&&taskinfos!=null){
            for (Taskinfo taskinfo : taskinfos) {
                Task task=new Task();
                BeanUtils.copyProperties(taskinfo,task);

                task.setExecuteTime(taskinfo.getExecuteTime().getTime());

                //添加到redis中
                addTaskToCache(task);
            }
        }

        log.info("数据库任务同步到redis");
    }

    /**
     * 清理缓存中的数据
     */
    private void clearCache() {

        Set<String> future = cacheService.scan(ScheduleConstants.FUTURE + "*");
        Set<String> topic = cacheService.scan(ScheduleConstants.TOPIC + "*");
        cacheService.delete(future);
        cacheService.delete(topic);
    }


    /**
     * 删除redis中的数据
     *
     * @param task
     */
    private void removeTaskFromCache(Task task) {

        //设置redis的key
        String key = task.getTaskType() + "_" + task.getPriority();


        //2.1 如果任务的执行时间小于当前时间 从List删除
        if (task.getExecuteTime() <= System.currentTimeMillis()) {

            /*index=0, 删除所有值等于value的元素; index>0, 从头部开始删除第一个值等于value的元素;
              index<0, 从尾部开始删除第一个值等于value的元素;*/
            cacheService.lRemove(ScheduleConstants.TOPIC + key, 0, JSON.toJSONString(task));

        }//2.2 从zset删除
        else {

            cacheService.zRemove(ScheduleConstants.FUTURE + key, JSON.toJSONString(task));

        }

    }


    /**
     * 删除任务 更新任务日志
     *
     * @param taskId
     * @param status
     * @return
     */
    private Task updateDb(Long taskId, int status) {

        Task task = null;

        try {
            //1.删除任务
            taskinfoMapper.deleteById(taskId);

            //更新任务日志
            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
            //更新任务状态
            taskinfoLogs.setStatus(status);
            taskinfoLogsMapper.updateById(taskinfoLogs);

            task = new Task();
            BeanUtils.copyProperties(taskinfoLogs, task);
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
        } catch (BeansException e) {
            log.error("task cancel exception taskId:{}", taskId, e);
        }

        return task;

    }


    /**
     * 把任务添加到Redis
     */
    private void addTaskToCache(Task task) {

        //设置redis的key
        String key = task.getTaskType() + "_" + task.getPriority();

        //获取五分钟之后的时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        long nextScheduleTime = calendar.getTimeInMillis();


        //2.1 如果任务的执行时间小于当前时间 存入List
        if (task.getExecuteTime() <= System.currentTimeMillis()) {

            cacheService.lLeftPush(ScheduleConstants.TOPIC + key, JSON.toJSONString(task));

        }//2.2 如果人物的执行时间大于当前时间 && 小于预设时间（未来五分钟） 存入zset中
        else if (task.getExecuteTime() > System.currentTimeMillis() && task.getExecuteTime() <= nextScheduleTime) {

            cacheService.zAdd(ScheduleConstants.FUTURE + key, JSON.toJSONString(task), nextScheduleTime);

        }

    }


    /**
     * 添加任务到数据库中
     *
     * @param task
     * @return
     */
    private boolean addTaskToDb(Task task) {

        boolean flage = false;


        try {
            //1.保存任务到任务表中
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task, taskinfo);

            //两个类中时间类型不一样 手动设置时间
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);


            //设置taskid
            task.setTaskId(taskinfo.getTaskId());


            //2.保存任务到任务信息表中
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo, taskinfoLogs);
            //设置乐观锁
            taskinfoLogs.setVersion(1);
            //设置任务状态   初始化
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogsMapper.insert(taskinfoLogs);

            flage = true;

        } catch (BeansException e) {

            e.printStackTrace();

        }

        return flage;



    }




}































